package cn.com.nes.site.controller.comecall;

import cn.com.nes.common.util.DateParamUtil;
import cn.com.nes.common.util.SysResult;
import cn.com.nes.mybatis.callcenter.mapper.CompanyAttachMapper;
import cn.com.nes.site.service.comecall.CallRecordsService;
import cn.com.nes.site.service.comecall.dto.CallRecordsDto;
import cn.com.nes.site.service.comecall.entity.CallRecords;
import cn.com.nes.site.service.comecall.entity.CompanyAttach;
import cn.com.nes.site.service.comecall.vo.CallOfTimeStatisticsVo;
import cn.com.nes.site.service.comecall.vo.CallQuantityStatisticsVo;
import cn.com.nes.site.service.comecall.vo.CallRecordsVO;
import cn.com.nes.site.service.comecall.vo.CallWorkOrderStatisticsVo;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v2/callRecords")
public class CallRecordsController {

    @Autowired
    private CallRecordsService callRecordsService;

    @Resource
    private CompanyAttachMapper companyAttachMapper;
    /**
     * 查询通话记录列表-分页（PC 端）
     *
     * @param vo
     * @param
     * @return
     */
    @PostMapping("getCallRecords")
    public SysResult getCallRecords(@RequestBody CallRecordsVO vo) {
        Page<CallRecordsDto> res;
        try {
            if (ObjectUtil.isEmpty(vo.getCompanyId())) {
                vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
            }
            if (ObjectUtil.isEmpty(vo.getCompanyAttachId())) {
                CompanyAttach companyAttach = companyAttachMapper.queryCompanyAttach(vo.getOperateUserCallCenterCompanyId());
                vo.setCompanyAttachId(companyAttach.getId());
            }
            vo.setCompanyAttachId(vo.getCompanyAttachId());
            if (!StrUtil.isNotBlank(vo.getInout())) {
                vo.setInout("全部");
            }
            res = callRecordsService.getCallRecords(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.error();
        }
        return SysResult.ok(res);
    }

    /**
     * 保存通话记录（通过各个服务中心的通讯程序调用此接口，进行通话记录的保存）
     *
     * @param vo
     * @param request
     * @return
     */
    @PostMapping("saveCallRecords")
    public SysResult saveCallRecords(@RequestBody List<CallRecords> vo, HttpServletRequest request) {
        String appId = request.getHeader("x-app-id");
        String secret = request.getHeader("x-secret");
        Map<String, Object> result = new LinkedHashMap<>();
        try {
            result.put("expectCount", vo.size());
            result.put("successCount", callRecordsService.saveCallRecords(appId, secret, vo));
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.error();
        }
        return SysResult.ok(result);
    }

    /**
     * 统计呼入呼出数量
     *
     * @param vo
     * @param
     * @return
     */
    @PostMapping("getCallQuantityStatistics")
    public SysResult callQuantityStatistics(@RequestBody CallQuantityStatisticsVo vo) {

        vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
        vo.setCompanyAttachId(vo.getCompanyAttachId());
        vo.setStartTime(DateParamUtil.handleStartTime(vo.getStartTime()));
        vo.setEndTime(DateParamUtil.handleEndTime(vo.getEndTime()));

        return SysResult.ok(callRecordsService.getCallQuantityStatistics(vo));
    }

    /**
     * 按日期统计呼入呼出数量
     *
     * @param vo
     * @param session
     * @return
     */
    @PostMapping("getCallOfTimeStatistics")
    public SysResult callOfTimeStatistics(@RequestBody CallOfTimeStatisticsVo vo, HttpSession session) {
        try {
            vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
            vo.setCompanyAttachId(vo.getCompanyAttachId());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StrUtil.isBlank(vo.getStartTime()) && StrUtil.isBlank(vo.getEndTime())) {//按天统计
                String endTime = format.format(new Date(new Date().getTime()));//今天天
                Instant instant = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime).toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
                String startTime = localDateTime.plusMonths(-1l).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));//前一个月
                vo.setStartTime(startTime);
                vo.setEndTime(endTime);
            }
            if (vo.getType() == null) {
                vo.setType(0);   //  默认按天统计
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return SysResult.ok(callRecordsService.getCallOfTimeStatistics(vo));
    }

    /**
     * 沟通记录统计
     *
     * @param vo
     * @param session
     * @return
     */
    @PostMapping("getCallWorkOrderStatistics")
    public SysResult callWorkOrderStatistics(@RequestBody CallWorkOrderStatisticsVo vo, HttpSession session) {
        vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
        vo.setCompanyAttachId(vo.getCompanyAttachId());
        vo.setStartTime(DateParamUtil.handleStartTime(vo.getStartTime()));
        vo.setEndTime(DateParamUtil.handleEndTime(vo.getEndTime()));

        return SysResult.ok(callRecordsService.getCallWorkOrderStatistics(vo));
    }

}
